const express = require("express");
const router = express.Router();
const url = require("url");
const axios =require("axios"); 
const getLocation = require("../tools/getLocation.js")
router.get("/weather",async (req,res) => {
    try{
        // const query = url.parse(req.url).query.split("&");
        // //存储对象形式的经纬度坐标
        // const lnglat = {}
        // for(i in query){
        //    query[i] = query[i].split("=")
        // }
        // lnglat[query.flat()[0]] = query.flat()[1];
        // lnglat[query.flat()[2]] = query.flat()[3];
        
        // // console.log(result)

        // //获取地理位置
        // const {data: resLocation} = await axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=f58766337111f56d9101db384fbea982&location=${lnglat.lng},${lnglat.lat}`);
        // const location = resLocation.regeocode.addressComponent
        // console.log(location) 
        // getLocation是获取地理编码的函数，传入的参数是req请求对象
        const location = await getLocation(req)
        // 天气响应数据 
        const {data: resWeather} = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?key=f58766337111f56d9101db384fbea982&city=${location.adcode}&output=JSON`);
        res.send(resWeather.lives[0]);
    }
    catch(err){
        console.log(err)
    }
});

module.exports = router;